package com.neiquan.backstage.resourec_manage.webaction;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.common.util.Strings;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;
import com.neiquan.backstage.pub.bsc.dao.po.Entrepreneur;
import com.neiquan.backstage.pub.bsc.dao.po.Lease;
import com.neiquan.backstage.pub.bsc.dao.po.Payment;
import com.neiquan.backstage.pub.bsc.dao.po.Station;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;
import com.neiquan.backstage.resourec_manage.PaymentService;
import com.neiquan.backstage.resourec_manage.ResourecLeaseService;
import com.neiquan.backstage.resourec_manage.ResourecStationService;

@Controller
@RequestMapping(value = "paymentAction", produces = { "text/json;charset=UTF-8" })
public class PaymentAction {
	private static Class<?> poc = Lease.class;
	private static Class<?> pocS = Station.class;
	private static Class<?> pocE = Entrepreneur.class;
	private static Class<?> pocP = Payment.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private EntrepreneurService entrepreneurService;
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private ResourecLeaseService resourecLeaseService;
	@Autowired
	private ResourecStationService resourecStationService;
	
	/**
	 * 	查看欠费
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"search"})
	public String search(String nameSend,HttpSession session){
		List list=new ArrayList();
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Lease> entitysL=(List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where memberId=?", memberId);
		if(entitysL==null||entitysL.size()<=0){
			return CommonResp.buildSuccessResp().toJsonString();
		}else{
			for(Lease lease:entitysL){
				int status=0;
				Integer leaseId = lease.getLeaseId();
				Long endTime1 = lease.getEndTime();
				Payment entityP1 = extraSpringHibernateTemplate.findFirstOneByPropEq(pocP, "leaseId", leaseId);
				if(entityP1==null){
					status=1;
				}
				Integer newlyStuats = lease.getNewlyStuats();
				String phone="";
				String name="";
				double arrearage=0;
				double sumRental=0;
				Long endTime=null;
				List<Payment> entityP=(List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate()
						.find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId,Payment.PAY_SUCCEE);
				Map<String, Object> map=new HashMap<String, Object>();
				if(entityP.size()<=0){
					Lease lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
					Integer entrepreneurId = lease1.getEntrepreneurId();
					Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
					if(entityE==null){
						return CommonResp.buildSuccessResp().toJsonString();
					}
					phone=entityE.getPhone();
					name=entityE.getName();
					sumRental = lease1.getSumRental();
					endTime=lease1.getStratTime();//可能有bug
				}else{
					Payment payment = entityP.get(0);
					int payLeaseId=payment.getLeaseId();
					Lease lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", payLeaseId);
					Integer entrepreneurId = lease1.getEntrepreneurId();
					Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
					if(entityE==null){
						return CommonResp.buildSuccessResp().toJsonString();
					}
					phone=entityE.getPhone();
					name=entityE.getName();
					sumRental = lease1.getSumRental();
					endTime = payment.getEndTime();
				}
				int numberMonth=0;
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(System.currentTimeMillis());
				int currentDayNum=calendar.get(Calendar.DAY_OF_MONTH);
				int currentYear = calendar.get(Calendar.YEAR);
				int currentMonth = calendar.get(Calendar.MONTH);
				int currentDay=calendar.get(Calendar.DATE);
				Calendar calendar1 = Calendar.getInstance();
				calendar1.setTimeInMillis(endTime);
				int endYear = calendar1.get(Calendar.YEAR);
				int endMonth = calendar1.get(Calendar.MONTH);
				int endDay=calendar1.get(Calendar.DATE);
				if(currentYear==endYear){
					if(currentMonth==endMonth){
						if(currentDay>endDay){
							int day=currentDay-endDay;
							arrearage=sumRental*day/currentDayNum;
						}
					}
					if(currentMonth>endMonth){
						int a=currentMonth-endMonth;
						if(currentDay>endDay){
							numberMonth=a;
							int day=currentDay-endDay;
							arrearage=(a*sumRental)+(sumRental*day/currentDayNum);
						}else{
							numberMonth=a-1;
							int day=endDay-currentDay;
							arrearage=(a*sumRental)-(sumRental*day/30);
						}
					}
				}else if(currentYear>endYear){
					Integer b=currentYear-endYear;
					numberMonth=b*12+currentMonth-endMonth;
					if(currentDay>endDay){
						int day=currentDay-endDay;
						numberMonth=b*12+currentMonth-endMonth+1;
						arrearage=(numberMonth*sumRental)+(sumRental*day/30);
					}else{
						int day=endDay-currentDay;
						numberMonth=b*12+currentMonth-endMonth;
						arrearage=(numberMonth*sumRental)-(sumRental*day/30);;
					}
				}
				
				if(name.indexOf(nameSend)!=-1){
					map.put("status", status);
					map.put("newlyStuats", newlyStuats);
					map.put("leaseId", leaseId);
					map.put("phone", phone);
					map.put("name", name);
					map.put("numberMonth", numberMonth);
					map.put("arrearage", String.format("%.2f", arrearage));
					map.put("endTime", endTime);
					map.put("endTime1", endTime1);
					list.add(map);
				}
			}
			return CommonResp.buildSuccessResp(list).toJsonString();
		}
	}

	/**
	 * 添加新增状态L付款对象
	 */
	@ResponseBody
	@RequestMapping(value={"addNewlyPayment"})
	public String addNewlyPayment(Integer leaseId,double totalRent,long rentTime) throws ParseException {
		Lease entityL1 = resourecLeaseService.queryById(leaseId);
		Integer entrepreneurId = entityL1.getEntrepreneurId();
		Lease entityL2 = resourecLeaseService.queryByEntrepreneurId(entrepreneurId, Lease.new_no, Lease.status_pass);
		Integer leaseId2 = entityL2.getLeaseId();
		Lease entityLN = resourecLeaseService.queryById(leaseId);
		String momentStationIds = entityLN.getMomentStationIds();
		double sumRental = entityLN.getSumRental();
		Lease entityLP = resourecLeaseService.queryByEntrepreneurId(entrepreneurId, Lease.new_no, Lease.status_pass);
		if(entityLN.getNewlyStuats()==Lease.new_yes&&entityLN.getNewlyStuats()==Lease.status_pass){
			List<Station> listS = resourecStationService.queryAllByLeaseId(leaseId, Station.status_lease);
			for(Station s:listS){
				s.setLeaseId(entityLP.getLeaseId());
				extraSpringHibernateTemplate.getHibernateTemplate().save(s);
				momentStationIds+=","+s.getStationId();
				sumRental+=s.getRental();
			}
			entityLP.setMomentStationIds(momentStationIds);
			entityLP.setSumRental(sumRental);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entityLP);
			extraSpringHibernateTemplate.getHibernateTemplate().delete(entityLN);
		}
		Payment entityP = new Payment();
		entityP.setLeaseId(leaseId2);
		entityP.setMode(Payment.PAY_LINE_BELOW);
		entityP.setStatus(Payment.PAY_SUCCEE);
		entityP.setStratTime(System.currentTimeMillis());
		entityP.setTotalRent(totalRent);
		entityP.setEntrepreneurId(entrepreneurId);
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(rentTime);
		long endTime = calendar.getTimeInMillis();
		entityP.setEndTime(endTime);
		extraSpringHibernateTemplate.getHibernateTemplate().save(entityP);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 查看缴费记录
	 */
	@ResponseBody
	@RequestMapping(value={"allRecord"})
	public String allRecord(Integer id) throws ParseException {
		List<Payment> listP = (List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("From Payment where leaseId=? and status=?", id,Payment.PAY_SUCCEE);
		return CommonResp.buildSuccessResp(listP).toJsonString();
	}
	/**
	 * 查询新增表
	 */
	@ResponseBody
	@RequestMapping(value={"findPayment"})
	public String findPayment(Integer leaseId) throws ParseException {
		double needPayment=0;
		Long endTime=null;
		Lease entityL = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		Long stratTime = entityL.getStratTime();
		double sumRental=entityL.getSumRental();
		Integer entrepreneurId = entityL.getEntrepreneurId();
		List<Lease> listL = (List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where entrepreneurId=? and newlyStuats=?", entrepreneurId,Lease.new_no);
		Lease lease2 = listL.get(0);
		Integer leaseId2 = lease2.getLeaseId();
		List<Payment> entityP=(List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId2,Payment.PAY_SUCCEE);
		Map<String, Object> map=new HashMap<String, Object>();
		if(entityP.size()<=0){
			Lease lease=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
//			endTime=lease.getStratTime();
//			map.put("needPayment", String.format("%.2f", needPayment));
//			map.put("endTime1", endTime);
			return CommonResp.buildSuccessResp("null").toJsonString();
		}else{
		Payment payment = entityP.get(0);
			int payLeaseId=payment.getLeaseId();
			Lease lease=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", payLeaseId);
			endTime = payment.getEndTime();
		}
		int numberMonth=0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(endTime);
		int currentYear = calendar.get(Calendar.YEAR);
		int currentMonth = calendar.get(Calendar.MONTH);
		int currentDay=calendar.get(Calendar.DATE);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(Calendar.YEAR, currentYear);
		calendar2.set(Calendar.MONTH, currentMonth-1);
		calendar2.set(Calendar.DATE, 1);
		calendar2.roll(Calendar.DATE, -1);
		int currentDayNum=calendar2.get(Calendar.DATE);
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTimeInMillis(stratTime);
		int endYear = calendar1.get(Calendar.YEAR);
		int endMonth = calendar1.get(Calendar.MONTH);
		int endDay=calendar1.get(Calendar.DATE);
		if(currentYear==endYear){
			if(currentMonth==endMonth){
				if(currentDay>endDay){
					int day=currentDay-endDay;
					needPayment=sumRental*day/currentDayNum;
				}
			}
			if(currentMonth>endMonth){
				int a=currentMonth-endMonth;
				if(currentDay>endDay){
					numberMonth=a;
					int day=currentDay-endDay;
					needPayment=(a*sumRental)+(sumRental*day/currentDayNum);
				}else{
					numberMonth=a-1;
					int day=endDay-currentDay;
					needPayment=(a*sumRental)-(sumRental*day/currentDayNum);
				}
			}
		}else if(currentYear>endYear){
			Integer b=currentYear-endYear;
			numberMonth=b*12+currentMonth-endMonth;
			if(currentDay>endDay){
				int day=currentDay-endDay;
				numberMonth=b*12+currentMonth-endMonth+1;
				needPayment=(numberMonth*sumRental)+(sumRental*day/currentDayNum);
			}else{
				int day=endDay-currentDay;
				numberMonth=b*12+currentMonth-endMonth;
				needPayment=(numberMonth*sumRental)-(sumRental*day/currentDayNum);;
			}
		}
		
		map.put("needPayment", String.format("%.2f", needPayment));
		map.put("endTime1", endTime);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}
	/**
	 * 查询是否欠费
	 */
	@ResponseBody
	@RequestMapping(value={"firstPayment"})
	public String firstPayment(Integer leaseId) throws ParseException {
		double arrearage=0;
		Long endTime=null;
		Lease lease1 = resourecLeaseService.queryById(leaseId);
		double sumRental=lease1.getSumRental();
		List<Payment> entityP=(List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId,Payment.PAY_SUCCEE);
		Map<String, Object> map=new HashMap<String, Object>();
		if(entityP.size()<=0){
			Lease lease=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
			endTime=lease.getStratTime();
		}else{
		Payment payment = entityP.get(0);
			endTime = payment.getEndTime();
		}
		int numberMonth=0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		int currentYear = calendar.get(Calendar.YEAR);
		int currentMonth = calendar.get(Calendar.MONTH);
		int currentDay=calendar.get(Calendar.DATE);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(Calendar.YEAR, currentYear);
		calendar2.set(Calendar.MONTH, currentMonth-1);
		calendar2.set(Calendar.DATE, 1);
		calendar2.roll(Calendar.DATE, -1);
		int currentDayNum=calendar2.get(Calendar.DATE);
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTimeInMillis(endTime);
		int endYear = calendar1.get(Calendar.YEAR);
		int endMonth = calendar1.get(Calendar.MONTH);
		int endDay=calendar1.get(Calendar.DATE);
		if(currentYear==endYear){
			if(currentMonth==endMonth){
				if(currentDay>endDay){
					int day=currentDay-endDay;
					arrearage=sumRental*day/currentDayNum;
				}
			}
			if(currentMonth>endMonth){
				int a=currentMonth-endMonth;
				if(currentDay>endDay){
					numberMonth=a;
					int day=currentDay-endDay;
					arrearage=(a*sumRental)+(sumRental*day/currentDayNum);
				}else{
					numberMonth=a-1;
					int day=endDay-currentDay;
					arrearage=(a*sumRental)-(sumRental*day/30);
				}
			}
		}else if(currentYear>endYear){
			Integer b=currentYear-endYear;
			numberMonth=b*12+currentMonth-endMonth;
			if(currentDay>endDay){
				int day=currentDay-endDay;
				numberMonth=b*12+currentMonth-endMonth+1;
				arrearage=(numberMonth*sumRental)+(sumRental*day/30);
			}else{
				int day=endDay-currentDay;
				numberMonth=b*12+currentMonth-endMonth;
				arrearage=(numberMonth*sumRental)-(sumRental*day/30);;
			}
		}
		
		map.put("numberMonth", numberMonth);
		map.put("arrearage", String.format("%.2f", arrearage));
		map.put("endTime", endTime);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}
	/**
	 * 添加付款对象
	 */
	@ResponseBody
	@RequestMapping(value={"addPayment"})
	public String addPayment(Integer leaseId,double totalRent,String rentTime,Integer monthNumber) throws ParseException {
		Payment entityP = new Payment();
		entityP.setLeaseId(leaseId);
		entityP.setMode(Payment.PAY_LINE_BELOW);
		entityP.setStatus(Payment.PAY_SUCCEE);
		entityP.setMonthNumber(monthNumber);
		entityP.setStratTime(System.currentTimeMillis());
		entityP.setTotalRent(totalRent);
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		entityP.setEndTime(dateFormat.parse(Strings.trimAndNotNull(rentTime)).getTime());
		Lease entityLN = resourecLeaseService.queryById(leaseId);
		Integer entrepreneurId = entityLN.getEntrepreneurId();
		entityP.setEntrepreneurId(entrepreneurId);
		String momentStationIds = entityLN.getMomentStationIds();
		double sumRental = entityLN.getSumRental();
		Lease entityLP = resourecLeaseService.queryByEntrepreneurId(entrepreneurId, Lease.new_no, Lease.status_pass);
		if(entityLN.getNewlyStuats()==Lease.new_yes&&entityLN.getNewlyStuats()==Lease.status_pass){
			List<Station> listS = resourecStationService.queryAllByLeaseId(leaseId);
			for(Station s:listS){
				s.setLeaseId(entityLP.getLeaseId());
				s.setState(Station.status_lease);
				extraSpringHibernateTemplate.getHibernateTemplate().save(s);
				momentStationIds+=","+s.getStationId();
				sumRental+=s.getRental();
			}
			entityLP.setMomentStationIds(momentStationIds);
			entityLP.setSumRental(sumRental);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entityLP);
			extraSpringHibernateTemplate.getHibernateTemplate().delete(entityLN);
		}
		extraSpringHibernateTemplate.getHibernateTemplate().save(entityP);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 恢复更换失败状态为正常状态
	 */
	@ResponseBody
	@RequestMapping(value={"recoverChange"})
	public String recoverChange(Integer leaseId) {
		Lease entityL=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
				entityL.setStatus(1);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entityL);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	/**
	 * 通过公司名查询该公司下lesaeId
	 */
	@ResponseBody
	@RequestMapping(value={"queryByEntNamelesaeId"})
	public String queryByEntNamelesaeId(String name) {
		Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "name", name);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Station> find = (List<Station>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("FROM Station s WHERE entrepreneur=? AND status==1",entrepreneurId );
		Station station = find.get(0);
		return CommonResp.buildSuccessResp(station).toJsonString();
	}
	
	/**
	 * 查询指定是lease对象
	 * @return
	 */
		@ResponseBody
		@RequestMapping(value={"queryLease"})
		public String queryLease(Integer leaseId) {
			Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
			return CommonResp.buildSuccessResp(entity).toJsonString();
		}
	/**
	 * 查询指定是Entrepreneur对象
	 */
		@ResponseBody
		@RequestMapping(value={"queryEntrepreneur"})
		public String queryEntrepreneur(Integer leaseId) {
			// TODO Auto-generated method stub
			Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
			Integer entrepreneurId = entity.getEntrepreneurId();
			Entrepreneur entrepreneur= extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
			return CommonResp.buildSuccessResp(entrepreneur).toJsonString();
		}
	/**
	* 查询去重是zone对象
	*/
	@ResponseBody
	@RequestMapping(value={"queryZones"})
	public String queryZones(Integer leaseId,HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Station> find = (List<Station>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("FROM Station s WHERE leaseId=? and memberId=? GROUP BY s.zone", leaseId,memberId);
		return CommonResp.buildSuccessResp(find).toJsonString();
	}	
	/**
	* 查询去重是zone对象
	*/
	@ResponseBody
	@RequestMapping(value={"queryStations"})
	public String queryStations(Integer leaseId) {
		// TODO Auto-generated method stub
		List<Station> find = extraSpringHibernateTemplate.findAllByPropEq(pocS, "leaseId", leaseId);
		return CommonResp.buildSuccessResp(find).toJsonString();
	}	
	/**
	 * 	查看欠费
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"listArrearage"})
	public String listArrearage(HttpSession session){
		List list=new ArrayList();
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Lease> entitysL=(List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where memberId=?", memberId);
		if(entitysL==null||entitysL.size()<=0){
			return CommonResp.buildSuccessResp().toJsonString();
		}else{
			for(Lease lease:entitysL){
				int status=0;
				Integer leaseId = lease.getLeaseId();
				Long endTime1 = lease.getEndTime();
				List<Payment> listP= (List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Payment WHERE leaseId=? and status=?)",leaseId,Payment.PAY_SUCCEE);
				if(listP.size()>0){
					Payment entityP1= listP.get(0);
					if(entityP1==null){
						status=1;
					}
				}
				Integer newlyStuats = lease.getNewlyStuats();
				String phone="";
				String name="";
				double arrearage=0;
				double sumRental=0;
				Long endTime=null;
				List<Payment> entityP=(List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate()
						.find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId,Payment.PAY_SUCCEE);
				Map<String, Object> map=new HashMap<String, Object>();
				if(entityP.size()<=0){
					Lease lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
					Integer entrepreneurId = lease1.getEntrepreneurId();
					Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
					if(entityE==null){
						return CommonResp.buildSuccessResp().toJsonString();
					}
					phone=entityE.getPhone();
					name=entityE.getName();
					sumRental = lease1.getSumRental();
					endTime=lease1.getStratTime();
				}else{
					Payment payment = entityP.get(0);
					int payLeaseId=payment.getLeaseId();
					Lease lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", payLeaseId);
					Integer entrepreneurId = lease1.getEntrepreneurId();
					Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
					if(entityE==null){
						return CommonResp.buildSuccessResp().toJsonString();
					}
					phone=entityE.getPhone();
					name=entityE.getName();
					sumRental = lease1.getSumRental();
					endTime = payment.getEndTime();
				}
				int numberMonth=0;
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(System.currentTimeMillis());
				int currentYear = calendar.get(Calendar.YEAR);
				int currentMonth = calendar.get(Calendar.MONTH)+1;
				int currentDay=calendar.get(Calendar.DATE);
				Calendar calendar2 = Calendar.getInstance();
				calendar2.set(Calendar.YEAR, currentYear);
				calendar2.set(Calendar.MONTH, currentMonth-1);
				calendar2.set(Calendar.DATE, 1);
				calendar2.roll(Calendar.DATE, -1);
				int currentDayNum=calendar2.get(Calendar.DATE);
				Calendar calendar1 = Calendar.getInstance();
				calendar1.setTimeInMillis(endTime);
				int endYear = calendar1.get(Calendar.YEAR);
				int endMonth = calendar1.get(Calendar.MONTH);
				int endDay=calendar1.get(Calendar.DATE);
				if(currentYear==endYear){
					if(currentMonth==endMonth){
						if(currentDay>endDay){
							int day=currentDay-endDay;
							arrearage=sumRental*day/currentDayNum;
						}
					}
					if(currentMonth>endMonth){
						int a=currentMonth-endMonth;
						if(currentDay>endDay){
							numberMonth=a;
							int day=currentDay-endDay;
							arrearage=(a*sumRental)+(sumRental*day/currentDayNum);
						}else{
							numberMonth=a-1;
							int day=endDay-currentDay;
							arrearage=(a*sumRental)-(sumRental*day/30);
						}
					}
				}else if(currentYear>endYear){
					Integer b=currentYear-endYear;
					numberMonth=b*12+currentMonth-endMonth;
					if(currentDay>endDay){
						int day=currentDay-endDay;
						numberMonth=b*12+currentMonth-endMonth+1;
						arrearage=(numberMonth*sumRental)+(sumRental*day/30);
					}else{
						int day=endDay-currentDay;
						numberMonth=b*12+currentMonth-endMonth;
						arrearage=(numberMonth*sumRental)-(sumRental*day/30);;
					}
				}
				if(arrearage>0){
					map.put("status", status);
					map.put("newlyStuats", newlyStuats);
					map.put("leaseId", leaseId);
					map.put("phone", phone);
					map.put("name", name);
					map.put("numberMonth", numberMonth);
					map.put("arrearage", String.format("%.2f", arrearage));
					map.put("endTime", endTime);
					map.put("endTime1", endTime1);
					list.add(map);
				}
			}
			return CommonResp.buildSuccessResp(list).toJsonString();
		}
	} 
	/**
	 * 	分页查询所有
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value={"list"})
	public String list(int pageIndex, int pageSize,HttpSession session){
		List list=new ArrayList();
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		 List<Lease> entitysL=(List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where memberId=?", memberId);
		if(entitysL==null||entitysL.size()<=0){
			return CommonResp.buildSuccessResp().toJsonString();
		}else{
		for(Lease lease:entitysL){
			int status=0;
			Integer leaseId = lease.getLeaseId();
			Long endTime1 = lease.getEndTime();
			Payment entityP1 = extraSpringHibernateTemplate.findFirstOneByPropEq(pocP, "leaseId", leaseId);
			if(entityP1==null){
				status=1;
			}
			Integer newlyStuats = lease.getNewlyStuats();
			String phone="";
			String name="";
			double arrearage=0;
			Long endTime=null;
			double sumRental=lease.getSumRental();
			List<Payment> entityP=(List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate()
					.find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId ,Payment.PAY_SUCCEE);
			Map<String, Object> map=new HashMap<String, Object>();
			if(entityP.size()<=0){
				Lease lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
				Integer entrepreneurId = lease1.getEntrepreneurId();
				Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
				if(entityE==null){
					return CommonResp.buildSuccessResp().toJsonString();
				}
				phone=entityE.getPhone();
				name=entityE.getName();
				endTime=lease1.getStratTime();
			}else{
				Payment payment = entityP.get(0);
				int payLeaseId=payment.getLeaseId();
				Lease lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", payLeaseId);
				Integer entrepreneurId = lease1.getEntrepreneurId();
				Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
				if(entityE==null){
					return CommonResp.buildSuccessResp().toJsonString();
				}
				phone=entityE.getPhone();
				name=entityE.getName();
				endTime = payment.getEndTime();
			}
			int numberMonth=0;
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(System.currentTimeMillis());
			int currentYear = calendar.get(Calendar.YEAR);
			int currentMonth = calendar.get(Calendar.MONTH);
			int currentDay=calendar.get(Calendar.DATE);
			Calendar calendar2 = Calendar.getInstance();
			calendar2.set(Calendar.YEAR, currentYear);
			calendar2.set(Calendar.MONTH, currentMonth-1);
			calendar2.set(Calendar.DATE, 1);
			calendar2.roll(Calendar.DATE, -1);
			int currentDayNum=calendar2.get(Calendar.DATE);
			Calendar calendar1 = Calendar.getInstance();
			calendar1.setTimeInMillis(endTime);
			int endYear = calendar1.get(Calendar.YEAR);
			int endMonth = calendar1.get(Calendar.MONTH);
			int endDay=calendar1.get(Calendar.DATE);
			if(currentYear==endYear){
				if(currentMonth==endMonth){
					if(currentDay>endDay){
						int day=currentDay-endDay;
						arrearage=sumRental*day/currentDayNum;
					}
				}
				if(currentMonth>endMonth){
					int a=currentMonth-endMonth;
					if(currentDay>endDay){
						numberMonth=a;
						int day=currentDay-endDay;
						arrearage=(a*sumRental)+(sumRental*day/currentDayNum);
					}else{
						numberMonth=a-1;
						int day=endDay-currentDay;
						arrearage=(a*sumRental)-(sumRental*day/currentDayNum);
					}
				}
			}else if(currentYear>endYear){
				Integer b=currentYear-endYear;
				numberMonth=b*12+currentMonth-endMonth;
				if(currentDay>endDay){
					int day=currentDay-endDay;
					numberMonth=b*12+currentMonth-endMonth+1;
					arrearage=(numberMonth*sumRental)+(sumRental*day/currentDayNum);
				}else{
					int day=endDay-currentDay;
					numberMonth=b*12+currentMonth-endMonth;
					arrearage=(numberMonth*sumRental)-(sumRental*day/currentDayNum);;
				}
			}
			map.put("status", status);
			map.put("newlyStuats", newlyStuats);
			map.put("leaseId", leaseId);
			map.put("phone", phone);
			map.put("name", name);
			map.put("numberMonth", numberMonth);
			map.put("arrearage", String.format("%.2f", arrearage));
			map.put("endTime", endTime);
			map.put("endTime1", endTime1);
			list.add(map);
		}
		return CommonResp.buildSuccessResp(list).toJsonString();
		}
	} 
	/**
	 * 添加出租对象
	 * @return
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value={"addLease"})
	public String addLease(@RequestParam("stationIds[]")Integer[] stationIds,Integer monthNumber,
			double totalPrice,String endTime,String startTime,Integer entrepreneurId,double sumRental,
			HttpSession session) throws ParseException {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		Lease entity = new Lease();
		Lease lease=extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "entrepreneurId", entrepreneurId);
		if(lease!=null){
			entity.setStatus(5);
		}else{
			entity.setStatus(0);
		}
		entity.setMonthNumber(monthNumber);
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		entity.setStratTime(dateFormat.parse(Strings.trimAndNotNull(startTime)).getTime());
		entity.setEndTime(dateFormat.parse(Strings.trimAndNotNull(endTime)).getTime());
		entity.setEntrepreneurId(entrepreneurId);
		entity.setTotalPrice(totalPrice);
		entity.setSumRental(sumRental);
		String momentStationIds="";
		for(Integer stationId1:stationIds){
			momentStationIds+=stationId1+",";
		}
		entity.setMemberId(memberId);
		entity.setMomentStationIds(momentStationIds);
		extraSpringHibernateTemplate.getHibernateTemplate().save(entity);
		Lease entity1 = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "entrepreneurId", entrepreneurId);
		Integer leaseId = entity1.getLeaseId();
		for(Integer stationId:stationIds){
			Station entityS = extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
			entityS.setLeaseId(leaseId);
			entityS.setState(3);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
		}
		
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 查询所有queryAll zone group by去重
	 * @return
	 */
		@ResponseBody
		@RequestMapping(value={"queryAll"})
		public String queryAll(HttpSession session) {
			AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
			Integer memberId = loginedUser.getMemberId();
			DetachedCriteria dc = DetachedCriteria.forClass(Station.class);
			dc.add(Restrictions.eq("memberId",memberId));
			dc.setProjection(Projections.alias(Projections.groupProperty("zone"),"zone"));
			 List<Station> list = extraSpringHibernateTemplate.findAllByCriteria(dc);
			return CommonResp.buildSuccessResp(list).toJsonString();
		}
		
		/**
		 * 生成工位图
		 * @param zone
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value={"stationImg"})
		public String stationImg(String zone,HttpSession session){
			AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
			Integer memberId = loginedUser.getMemberId();
			List<Criterion> criterions = new ArrayList<>();
			criterions.add(Restrictions.eq("memberId", memberId));
			criterions.add(Restrictions.eq("zone", zone));
			Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
			DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.build(Station.class, criterion);
			List<Station> list = extraSpringHibernateTemplate.findAllByCriteria(queryCountCriteria);
			return CommonResp.buildSuccessResp(list).toJsonString();
		}
	
}
